# 绘制折线图和饼图

from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE, XL_DATA_LABEL_POSITION, XL_LEGEND_POSITION
from pptx.util import Inches, Pt


def use_line():
    ppt = Presentation()
    # 添加幻灯片
    slide = ppt.slides.add_slide(ppt.slide_layouts[6])
    # 封装图标数据
    chart_data = CategoryChartData()
    # 分组数据
    chart_data.categories = ['第一季度', '第二季度', '第三季度', '第四季度']
    # 具体数据
    chart_data.add_series('2020', (19, 23, 45, 10))
    chart_data.add_series('2021', (17, 18, 22, 9))
    chart_data.add_series('2022', (21, 22, 40, 11))

    # 绘制图表 -- 柱状图 - COLUMN_CLUSTERED  |  折线图- LINE
    x = Inches(1)
    y = Inches(1)
    cx = Inches(8)
    cy = Inches(5)
    chart = slide.shapes.add_chart(XL_CHART_TYPE.LINE, x, y, cx, cy, chart_data).chart
    chart.chart_style = 11  # 支持 1-48 种样式主题
    chart.font.size = Pt(8)

    # 单独设置横轴坐标
    category_axis = chart.category_axis
    category_axis.tick_labels.font.size = Pt(15)  # 设置 x 轴的字体
    category_axis.has_major_gridlines = True  # 添加竖道

    # 设置折线图上的显示
    plot = chart.plots[0]
    plot.has_data_labels = True
    plot.data_labels.position = XL_DATA_LABEL_POSITION.INSIDE_BASE  # 设置标签显示位置

    # 设置图例
    chart.has_legend = True
    chart.legend.font.size = Pt(15)
    chart.legend.position = XL_LEGEND_POSITION.LEFT     # 图例位置
    chart.legend.include_in_layout = False      # 保证数据不会重叠

    ppt.save('../02.py_pptFile/06.ppt绘制图表样式_折线图.pptx')

def use_pie():
    ppt = Presentation()
    # 添加幻灯片
    slide = ppt.slides.add_slide(ppt.slide_layouts[6])
    # 封装图标数据
    chart_data = CategoryChartData()
    # 分组数据
    chart_data.categories = ['第一季度', '第二季度', '第三季度', '第四季度']
    # 具体数据
    chart_data.add_series('季度销售比例', (19, 23, 45, 10))

    # 绘制图表 -- 柱状图 - COLUMN_CLUSTERED  |  折线图- LINE  |  饼图- PIE
    x = Inches(1)
    y = Inches(1)
    cx = Inches(8)
    cy = Inches(5)
    chart = slide.shapes.add_chart(XL_CHART_TYPE.PIE, x, y, cx, cy, chart_data).chart
    chart.chart_style = 11  # 支持 1-48 种样式主题
    chart.font.size = Pt(8)

    # 设置饼图上的显示
    plot = chart.plots[0]
    plot.has_data_labels = True
    plot.data_labels.position = XL_DATA_LABEL_POSITION.OUTSIDE_END  # 设置标签显示位置
    # plot.data_labels.number_format = '0%'

    # 设置图例
    chart.has_legend = True
    chart.legend.font.size = Pt(15)
    chart.legend.position = XL_LEGEND_POSITION.LEFT     # 图例位置
    chart.legend.include_in_layout = False      # 保证数据不会重叠

    ppt.save('../02.py_pptFile/06.ppt绘制图表样式_饼图.pptx')


if __name__ == '__main__':
    use_line()
    use_pie()






